<template>
  <div  class="bus-card" v-if="!cardloading">
    <el-menu
      @select="handleSelect"
      :router="active"
      class="el-menu-vertical-demo">
      <el-menu-item class="card" style="padding:0" v-for="(item, index) in cardListRender" :index="handleSplit(item._id, item.customer)" :key="index" :class="[{'custom-is-active': $route.path.split('/')[4] === item._id}, 'card-priority' + item.priority]">
          <label class="fake-checkbox" :class="{'visible': batch.isBatchShow}" v-on:click.stop="">
            <input type="checkbox" class="fbox" :value="item._id" v-model.trim="item.checked" @change="checkThis(item.checked)">
            <span></span>
            <i class="fake-label"></i>
          </label>
        <el-tooltip :open-delay="150" :value="!provideData.show" :disabled="!provideData.show" placement="right" popper-class="card-tooltip" :visibleArrow="false" effect="light" transition="fade-leave">
          <div slot="content" class="card-detail">
            <div class="card-detail-tittle">{{$t('business.businessContent')}}</div>
            <table>
              <tbody valign="top">
              <template v-for="(i,index) in item.businessType.detail">
                <tr class="card-detail-item">
                  <td class="data-name">{{i.name}}</td>
                  <td class="break-all">{{i.value}}</td>
                </tr>
              </template>
              </tbody>
            </table>
          </div >
          <div style="padding:8px 5px 7px 0">
            <div class="one">
              <!--<i :class="['card-priority' + item.priority]" class="iconfont priority"></i>-->
              <p class="font14 card-step">
                <span class="card-step-item">{{ item.businessType.name }}</span>
                <span style="padding:0 5px"> - </span>
                <span class="card-step-item" :class="item.businessStep.type">{{item.businessStep.name}}</span>
              </p>
              <el-badge  v-show="item.noRead" is-dot :hidden="!item.noRead" class="card-badge">&nbsp;&nbsp;</el-badge>
              <p class="font12 card-time">
                <!-- 稍后处理 -->
                <!-- <i class="iconfont icon-shaohouchuli" v-show="item.laterProcess"></i> -->
                  <i  :class="{['flow-icon' + (item.laterProcessColor ? item.laterProcessColor : '')]: true}" class="iconfont icon-shaohouchuli" v-show="item.laterProcess"></i>
                {{ item.createTime }}
              </p>
            </div>
            <div class="two">
              <div class="card-left">
                <i :class="{['icon-chaoshi__' + $i18n.locale]: item.processTimeout}" class="iconfont process-timeout"></i>
                <i class="iconfont icon-yiguanzhu" :class="item.follow"></i>
              </div>
              <div class="card-right">
                <div class="card-customer">
                  <div :class="[item.userName.className]" class="fl customer-name">{{item.userName.name}}</div>
                  <div class="creator-master">
                    <span class="name fl">{{ item.agentBefore }}</span>
                    <span class="iconfont icon-dailingqu fl"></span>
                    <span class="name fl" v-show="tabType !== 'business_undeal'">{{item.agentAfter}}</span>
                    <span class="name fr tasktome" v-show="tabType === 'business_undeal'" @click.stop="setTaskToMe(item._id)">{{$t('business.received')}}</span>
                  </div>
                </div>
                <div class="summary" style="display: -webkit-box;-webkit-box-orient: vertical;">
                  {{item.businessType.summary.join(' | ')}}
                </div>
              </div>
            </div>
          </div>
        </el-tooltip>
      </el-menu-item>
    </el-menu>
    <no-record v-if="cardListRender && cardListRender.length<=0"></no-record>
    <!-- 批处理-->
    <div class="batch_cover" :class="{'navMenuState': navMenuState}" v-show="batch.isBatchShow"></div>
    <div class="batch_btm" v-show="batch.isBatchShow"></div>
    <div class="batch" :class="{'show': batch.isBatchShow, 'navMenuState': navMenuState}">
      <el-checkbox v-model.trim="batch.allChecked" @change="checkAll()">{{$t('public.checkAll')}}</el-checkbox>
      <card-batch v-if="batch.operator"
                  :tabType="tabType"
                  :batchOperator="batch"
                  @exportExcel="exportCustom"
                  @deleteTip="deleteTip"
                  @checkNone="checkNone"
                  @batchAssign="batchAssign"
                  @batchReceive="batchReceive"
        >
        <template slot="batchAssign">
          <div class="novice-boot-box-wrap" style="position: relative" v-if="!getNoviceKeyStatus.businessBatchAssign">
            <div class="novice-circle-group " style="position: absolute;top: 3px;right: -23px">
              <div class="novice-circle4"></div>
              <div class="novice-circle3"></div>
              <div class="novice-circle2"></div>
              <div class="novice-circle1"></div>
            </div>
            <div style="position: absolute;top: -90px;left:0 ;padding-bottom: 10px;z-index: 100;">
              <novice-boot
                NoviceKey="businessBatchAssign"
                :NoviceArr="[{title: '', text: $t('business.assignHelp')}]"
                @updateGuidanceSuccess="updateGuidanceSuccess"
              ></novice-boot>
            </div>
          </div>
        </template>
        <template slot="batchExecute">
          <div class="novice-boot-box-wrap" style="position: relative" v-if="!getNoviceKeyStatus.businessBatchExecute">
            <div class="novice-circle-group " style="position: absolute;top: 3px;right: -23px">
              <div class="novice-circle4"></div>
              <div class="novice-circle3"></div>
              <div class="novice-circle2"></div>
              <div class="novice-circle1"></div>
            </div>
            <div style="position: absolute;top: -90px;left:0 ;padding-bottom: 10px;z-index: 100;">
              <novice-boot
                NoviceKey="businessBatchExecute"
                :NoviceArr="[{title: '', text: $t('business.executeHelp')}]"
                @updateGuidanceSuccess="updateGuidanceSuccess"
              ></novice-boot>
            </div>
          </div>
        </template>
        <template slot="batchExecutePopover" slot-scope="slotProps">
          <el-popover
            ref="popover"
            placement="top"
            width="120"
            trigger="manual"
            popper-class="padding-no-tooltip"
            v-model="batchBusiness.show"
            :disabled="slotProps.item.enabled"
            >
            <p class="batch-step"
               v-for="item in batchBusiness.operateSelect"
               @click.stop="showTaskAction(item.value)"
            >{{item.label}}</p>
            <p class="batch-step pink" @click.stop="showTaskBack('back')">{{$t('business.return')}}</p>
            <el-tooltip slot="reference" effect="dark" :disabled="!slotProps.item.enabled" :content="slotProps.item.tooltipContent" placement="top-start">
              <span class="option" @click="batchExecute(slotProps.item.action, slotProps.item.enabled)" :class="!slotProps.item.enabled ? '': 'disabled'">
                <i :class="slotProps.item.class"></i>{{$t(slotProps.item.name)}}
              </span>
            </el-tooltip>
          </el-popover>
        </template>
      </card-batch>
    </div>
    <custom-export :exportDialog="exportDialog" @export="exportExcel" :exportType="exportType"></custom-export>
    <!--批量分配工单组件-->
    <batch-assign ref="batchAssign" @batchAssignSuc="batchAssignSuc"></batch-assign>
    <!--批量执行工单组件-->
    <batch-execute ref="batchExecute" @batchExecuteSuc="batchExecuteSuc"></batch-execute>
  </div>
</template>
<script>
  import CustomerAvatar from '@/components/ui-modules/customer-avatar/CustomerAvatar'
  import CardBatch from '@/components/public-modules/card/CardBatch'
  import NoRecord from '@/components/public-modules/card/NoRecord'
  import BatchAssign from './BatchAssign'
  import BatchExecute from './BatchExecute'
  import CustomExport from './customExport.vue'
  import * as gtypes from '@/store/mutation-types'
  import * as uuid from 'uuid'
  import noviceBoot from '@/components/public-modules/novice-boot/index.vue'
  import { isHasFunc, deepClone, timeFormat, getCache } from '@/utils/m7Utils.js'
  import {getFlowAction, getFlowStepActionById, sortBusinessFields, getStartStep, getStepRoles,getStepQueues, getQueueAgents, getRoleAgents, arrayContainsStr} from '@/utils/workflowUtils'
  import http from '@/store/api/http'
  export default {
    name: 'BusinessCard',
    /**
     * [props 该组件所需要的参数]
     * @type {
     *   cardList    相关业务的crad数组
     *   type        业务类型
     *   count       卡片条数
     * }
     */
    props: {
      allCount: Number,
      // 我的工单isRead,查询数量使用
      quAction: String, // 删除工单，发送工单数量请求
      qu: Object, // 删除工单，工单条件
      cardList: Array,
      type: String,
      tabType: String,
      loading: Boolean,
      condition: Object,
      clearChecked: {type: Number, default: 0},
      laterProcessData:Array
    },
    inject: ['provideData'],
    data () {
      return {
        active: true, // 是否使用路由
        cardloading: true,
        batch: {
          batchItem: [],
          allChecked: false,
          isBatchShow: false,
          checkedCount: 0,
          operator: [
          ],
          // 公共批处理
          operatorCommon: [
          ],
          // 待领取tab下批处理
          operatorUndeal: [
            {name: 'business.batchReceive', class: 'icon-pilianglingqu', action: 'batchReceive'}
          ],
          // 我的代办tab下批处理
          operatorMy: [
            { name: 'business.batchExecute',
              class: 'icon-piliangchuli',
              action: 'batchExecute',
              tooltipContent: this.$t('business.executeSearchTip'),
              enabled: true, // 是否禁用
              popover: 'batchExecutePopover'
            }
          ]
        },
        // 存放批处理的信息
        batchBusiness: {
          show: false,
          operateSelect: [], // 步骤动作
          argu: {} // 数量，条件参数
        },
        checked: false,
        finish: 'b-step',
        sessionId: this.$store.state.session.sessionId,
        // 工单自定义导出提示框
        exportDialog: {
          isShow: false,
          type: 'export',
          headers: [
            {name: this.$t('business.businessNumber'), value: 'number', default: true},
            {name: this.$t('business.customerName'), value: 'name', default: true},
            {name: this.$t('business.phone'), value: 'phone', default: true},
            {name: this.$t('business.priorityLabel'), value: 'priority', default: true},
            {name: this.$t('business.businessFlow'), value: 'flow', default: true},
            {name: this.$t('business.businessStep'), value: 'step', default: true},
            {name: this.$t('business.lastStep'), value: 'lastStep', default: false, prompt: this.$t('business.lastStepTip')},
            {name: this.$t('business.businessStatus'), value: 'status', default: true},
            {name: this.$t('business.master'), value: 'master', default: true},
            {name: this.$t('business.callNum'), value: 'callId', default: true},
            {name: this.$t('call.callNumber'), value: 'CALL_SHEET_ID', default: false},
            {name: this.$t('webchat.exportHead.sessionID'), value: 'webChatId', default: false},
            {name: this.$t('business.chatSatisfaction'), value: 'webChatCsr', default: false},
            {name: this.$t('business.customFields'), value: 'customFields', default: true},
            {name: this.$t('business.backInfo'), value: 'backInfo', default: true},
            {name: this.$t('business.createTime'), value: 'createTime', default: false},
            {name: this.$t('business.firstCreateTime'), value: 'firstCreateTime', default: false},
            {name: this.$t('business.creator'), value: 'creator', default: false},
            {name: this.$t('business.receiveTimes'), value: 'receiveTimes', default: false},
            {name: this.$t('business.stepsTime'), value: 'stepsInfo', default: false},
            {name: this.$t('business.circulationPath'), value: 'circulationPath', default: false},
            {name: this.$t('business.processEndTime'), value: 'processEndTime', default: false},
            {name: this.$t('business.callAppraise'), value: 'callAppraise', default: false},
            {name: this.$t('business.businessAppraise'), value: 'businessAppraise', default: false},
            {name: this.$t('business.allCustomer'), value: 'customer', default: false},
            {name: this.$t('business.businessCreationMode'), value: 'createMode', default: false},
            {name: this.$t('webchat.relationBusiness'), value: 'relatedBusiness', default: false}
          ],
          select: [],
          downloadAgents: [],
          agents: [],
          fileType: 'csv'
        },
        exportType: this.$store.state.isRealTimeExport ? 'real' : '', // real实时导出任务
        // 引导呼吸灯状态
        getNoviceKeyStatus: {}
      }
    },
    computed: {
      cardListRender () {
        // 防止getCache没取回就执行computed
        if (this.cardloading) {
          return []
        }
        let hh = []
        if(this.laterProcessData.length>0){
          hh = this.laterProcessData
        }else{
          hh = this.$store.state[this.type][this.type + 'List'].list || []
        }
        let items = []
        for (let i = 0; i < hh.length; i++) {
          let item = hh[i]
          let one = {}
          one.userName = this.name(item)
          // one.custStatus = this.custStatus(item.cust_status)
          one.businessType = this.businessType(item)
          one.agentAfter = this.agentAfter(item.master)
          one.agentBefore = this.agentBefore(item.createUser)
          one.businessStep = this.businessStep(item.flow, item.status, item.step)
          one.createTime = timeFormat(item.createTime, 'card')
          one._id = item._id
          one.customer = item.customer
          one.processTimeout = item.processTimeout
          one.priority = item.priority
          one.follow = 'none'
          one.stepId = item.step
          one.noRead = item.isReadFlag === false
          // 稍后处理
          one.laterProcess = this.tabType === 'business_my' && item.laterProcess
          one.laterProcessColor = this.tabType === 'business_my' && item.laterProcessColor
          if (item.followedAgents && item.followedAgents.indexOf(this.sessionId) !== -1) {
            one.follow = ''
          }
          items.push(one)
        }
        return items
      },
      navMenuState () {
        return this.$store.state.navMenuState || false
      }
    },
    methods: {
      // 引导状态更新
      updateGuidanceSuccess () {
        let guidance = this.$getCache('guidance')
        this.getNoviceKeyStatus = guidance || {'businessBatchAssign': true, 'businessBatchExecute': true} // 服务不对，或者是没有这个对象时，默认不显示。webchatSessionLocking为气泡的key
      },
      // 领取工单
      setTaskToMe (id) {
        if (this.tabType !== 'business_undeal') {
          return
        }
        window._hmt && window._hmt.push(['_trackEvent', '工单', '工单领取（卡片处）'])
        this.$store.dispatch('setTaskToMe', id).then(() => {
          this.$store.dispatch('refreshUndealNum')
          this.$store.commit('business/REFRESH_LEFT', Math.random())
          this.$router.push({path: '/index/business'})
        })
      },
      businessType (item) {
        let businessFlows = this.$getCache('businessFlow') || []
        for (let i = 0; i < businessFlows.length; i++) {
          if (businessFlows[i]._id === item.flow) {
            let {name, showFields, fields} = businessFlows[i]
            let step = getStartStep(businessFlows[i])
            let stepFields = step.stepFields || []
            let detail = [{name: this.$t('business.businessNumber'), value: item.number}]
            let summary = []
            sortBusinessFields(stepFields, fields, item, detail, 'card')
            if (showFields && showFields.length) {
              detail.forEach((item) => {
                if (showFields.indexOf(item._id) !== -1 && item.value) {
                  summary.push(item.value)
                }
              })
            }
            return {name, detail, summary}
          }
        }
        try {
          const data = {
            env: {
              browser: {name: 'Chrome', version: '67.0.3396.99'},
              os: 'Mac',
              userAgent: 'Mozilla/5.0'
            },
            extra: {
              componentName: '工单卡片'
            },
            errorType: 'TypeError',
            message: '工单卡片',
            referrer: 'http://kf.com/customer',
            stacktrace: {
              frames: []
            },
            trimHeadFrames: 1,
            url: '',
            exception: {
              values: [{
                type: 'TypeError',
                value: '错误信息：工单卡片信息item.flow：' +
                (item.flow || '') +
                '   item.number：' + item.number + '工单类型flows长度：' + businessFlows.length,
                stacktrace: {
                  frames: []
                }
              }]
            }
          }
          let req = {
            data,
            action: 'app.collect.collectVueErrorInfo'
          }
          http.fetch(req, 'post')
            .then((res) => {
            })
            .catch(err => {
              console.error(err)
            })
        } catch (err) {
          console.log(err)
        }

        return {name: '', detail: [], summary: []}
      },
      businessStep (flowId, status, step) {
        let businessStep = {name: '', type: ''}
        let businessFlows = this.$getCache('businessFlow')
        if (!businessFlows) {
          return businessStep
        }
        let flow = null
        for (let i = 0; i < businessFlows.length; i++) {
          if (businessFlows[i]._id === flowId) {
            flow = businessFlows[i]
            break
          }
        }
        if (status !== 'complete' && status !== 'cancel') {
          businessStep.type = 'b-step'
        } else {
          businessStep.type = 'finish'
        }
        let steps = flow ? flow.steps : []
        for (let i = 0; i < steps.length; i++) {
          var stepsItem = steps[i]
          if (stepsItem._id === step) {
            businessStep.name = stepsItem.name
            break
          }
        }
        return businessStep
      },
      agentAfter (master) {
        if (master === '') {
          return ''
        } else {
          let agent = this.$agentsMap() || {}
          return agent[master] ? agent[master].displayName : ''
        }
      },
      agentBefore (createUser) {
        let agent = this.$agentsMap() || {}
        return agent[createUser] ? agent[createUser].displayName : ''
      },
      name (item) {
        let name = ''
        let className = ''
        if (!item.customer) {
          name = this.$t('customer.customerSlot.unlocation')
          className = 'unknowCus'
        } else if (!item.name) {
          name = this.$t('business.hasRemoveCus')
          className = 'deleteCus'
        } else {
          name = item.name
        }
        return {className, name}
      },
      // 按照 卡片的_id不同设置不同路由
      handleSplit (index, customerId) {
        return '/index/' + this.type + '/' + this.tabType + '/' + index + '/' + (customerId || 'no-customer-bus')
      },
      handleSelect (index) {
        this.$store.commit('business/REFRESH_BUS_RIGHT', Math.random())
        // 是否已读
        let _id = index.split('/')[4]
        this.cardListRender.some((item) => {
          if (item._id === _id && item.noRead === true) {
            this.$store.dispatch('readBusiness', {_id: _id, menu: this.qu.menu}).then(() => {
              this.$store.dispatch('refreshUndealNum')
            })
            this.$store.commit('business/CHANGE_READ_STATUS', _id)
            return true
          }
        })
        this.$emit('changeCardItem', index)
      },
      getChecked () { // 单选获取数组
        return this.cardListRender.filter(item => item.checked).map(item => item._id)
      },
      checkThis (checked, event) { // 单个选中传送数组和展示批量
        let checkedArr = this.getChecked()
        let isBatchShow = checkedArr.length > 0
        this.batch.allChecked = checkedArr.length === this.$store.state.business.businessList.count
        this.batch.batchItem = checkedArr
        this.batch.isBatchShow = isBatchShow
        this.batch.checkedCount = checkedArr.length
      },
      checkAll () { // 全选&取消全选
        this.batch.isBatchShow = this.batch.allChecked
        let inputs = this.$el.getElementsByClassName('fbox')
        this.cardListRender.forEach((item) => {
          item.checked = this.batch.allChecked
        })
        for (let i = 0; i < inputs.length; i++) { // 升级之后有bug需要手动将checkbox调整为相应状态
          inputs[i].checked = this.batch.allChecked
        }
        if (this.$store.state.business.businessList.more) {
          this.batch.checkedCount = this.batch.allChecked ? this.$t('public.moreThan2') + this.$store.state.business.businessList.count : 0
        } else {
          if (this.allCount) {
            this.batch.checkedCount = this.allCount
          } else {
            this.batch.checkedCount = this.batch.allChecked ? this.$store.state.business.businessList.count : 0
          }
        }
      },
      checkNone (self) {
        let that
        if (self && self.$refs) {
          that = self
        } else {
          that = this
        }
        that.batch.allChecked = false
        that.batch.batchItem = []
        that.batch.isBatchShow = false
        that.cardListRender.forEach((item) => {
          item.checked = false
        })
      },
      getCurrentDateTime () {
        let date = new Date()
        let year = date.getFullYear()
        let month = date.getMonth()
        let day = date.getDate()
        let h = date.getHours()
        let m = date.getMinutes()
        let s = date.getSeconds()
        month = month + 1 > 9 ? month + 1 : '0' + (month + 1)
        day = day > 9 ? day : '0' + day
        h = h > 9 ? h : '0' + h
        m = m > 9 ? m : '0' + m
        s = s > 9 ? s : '0' + s
        return year + '-' + month + '-' + day + ' ' + h + '-' + m + '-' + s
      },
      batchAssignSuc () {
        this.checkNone()
        // this.$store.dispatch('refreshUndealNum')
        this.$store.commit('business/REFRESH_LEFT', Math.random())
      },
      exportExcel (type) {
        if (this.exportDialog.select.length === 0) {
          this.$message.error(this.$t('business.exportSelectOne'))
          return
        }
        // 高级搜索条件
        let data = {}
        if (this.batch.allChecked) {
          data = deepClone(this.$store.state.business.businessCondition)
        } else {
          data = {_id: {$in: this.batch.batchItem}}
        }
        if (this.tabType === 'business_undeal' || this.tabType === 'business_my') {
          data.flag = 'kf'
        }
        let headers = []
        let sessionId = this.$store.state.session.sessionId
        this.exportDialog.headers.forEach((item) => {
          if (this.exportDialog.select.indexOf(item.value) !== -1) {
            headers.push(item.value)
          }
        })
        if (type === 'task') {
          let downloadAgents = this.exportDialog.downloadAgents
          if (!downloadAgents.length) {
            return this.$message.error('至少选择一个可下载座席')
          }
          let exportData = {condition: data, headers, downloadAgents}
          if (this.exportType === 'real') {
            exportData.fileType = this.exportDialog.fileType
          }

          this.$store.dispatch('addExportTask', exportData).then((res) => {
            if (res.success) {
              this.checkNone()
              this.exportDialog.isShow = false
              this.$message.success(this.$t('business.exportExcel50000' + this.exportType))
              window.localStorage.setItem(sessionId + 'businessExportHeaders', JSON.stringify(headers))
            }
          })
        } else {
          data.headers = headers
          let _exportObj = {
            name: this.$t('business.exportName') + this.getCurrentDateTime(),
            id: uuid.v1()
          }
          this.$store.commit(gtypes.SET_EXPORTLIST, _exportObj)
          this.$store.dispatch('exportBusiness', data).then((res) => {
            this.$store.commit(gtypes.DEL_EXPORTLIST, _exportObj)
            if (res.success) {
              window.localStorage.setItem(sessionId + 'businessExportHeaders', JSON.stringify(headers))
            }
          })
          this.checkNone()
          this.exportDialog.isShow = false
        }
      },
      handleDeleteTip (num) {
        this.$confirm(this.$t('business.businessDelete', {num}), this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then(() => {
          this.deleteBus(this)
        }).catch(() => {
        })
      },
      deleteTip () {
        if (this.batch.allChecked) {
          this.$store.dispatch(this.quAction, this.qu).then((res) => {
            if (res.success) {
              const _num = res.count
              this.handleDeleteTip(_num)
            }
          })
        } else {
          this.handleDeleteTip(this.batch.checkedCount)
        }
      },
      // 工单批量分配
      async batchAssign () {
        // 同一工单类型和工单步骤的工单
        window._hmt && window._hmt.push(['_trackEvent', '工单', '工单批量分配（可点击状态的）'])
        let step = ''
        let isValide = false
        if ((this.qu.flow instanceof Array) && this.qu.flow.length === 1 && this.qu.step) {
          // 高级搜索筛选
          isValide = true
          if((this.qu.step instanceof Array) && this.qu.step.length === 1){
            step = this.qu.step[0]
          }
        }
        if (!isValide) {
          return
        }
        let roles = getStepRoles(step)
        let queues = getStepQueues(step)
        let roleAgentList = []
        let queueAgentList = []
        roleAgentList = getRoleAgents(roles, true)
        queueAgentList = await getQueueAgents(queues, true)
        let agents = [...new Set(roleAgentList.concat(queueAgentList))]
        if (roles[0] === 'busCreateUser') {
          // 正常情况，不可能进这里，流转到工单创建人的工单会直接填处理人，不会自动分配
          return
        }
        if (this.batch.allChecked) {
          this.$store.dispatch(this.quAction, this.qu).then((res) => {
            if (res.success) {
              let _num = res.count || 0
              this.$refs.batchAssign.open({count: _num, condition: this.qu, agents: agents, ids: []})
            }
          })
        } else {
          this.$refs.batchAssign.open({count: this.batch.checkedCount, condition: {}, agents: agents, ids: this.batch.batchItem})
        }
      },
      // 批量处理工单
      batchExecute (action, enabled) {
        if (enabled) {
          // 统计埋点
          window._hmt && window._hmt.push(['_trackEvent', '工单', '工单批量处理（不可点击状态的）'])
          return
        }
        window._hmt && window._hmt.push(['_trackEvent', '工单', '工单批量处理（可点击状态的）'])
        let promise = null
        // 缓存 工单条件，count，提交时使用
        if (this.batch.allChecked) {
          promise = this.$store.dispatch(this.quAction, this.qu).then((res) => {
            if (res.success) {
              let _num = res.count || 0
              this.batchBusiness.argu = {total: _num, condition: deepClone(this.qu)}
              delete this.batchBusiness.argu.condition.queryCount
              delete this.batchBusiness.argu.condition.page
              delete this.batchBusiness.argu.condition.morePage
            }
          })
        } else {
          promise = new Promise((resolve) => {
            this.batchBusiness.argu = { total: this.batch.checkedCount, ids: this.batch.batchItem }
            resolve()
          })
        }
        promise.then(() => {
          // 生成工单动作
          this.batchBusiness.operateSelect = []
          this.batchBusiness.show = true
          let step = null
          if((this.qu.step instanceof Array) && this.qu.step.length === 1){
            step = this.$getCache('businessFlowStep', this.qu.step[0])
          }
          let actions = step && step.actions ? step.actions : []
          let role = []
          let businessRole = []
          let businessQueue = []
          let mixedBizScope = []
          // mixedBizScope 角色或技能组 role之前单角色
          mixedBizScope = this.$store.state.session.user.mixedBizScope ? deepClone(this.$store.state.session.user.mixedBizScope) : deepClone(this.$store.state.session.user.role)
          if (this.tabType === 'business_my') {
            if (this.batch.operatorMy[0].createUser && this.batch.operatorMy[0].createUser === 'myself') {
              mixedBizScope.push('busCreateUser')
            }
          }
          // 符合动作角色或者技能组的坐席都有处理权限
          for (let i = 0; i < actions.length; i++) {
            var actionsItem = actions[i]
            // 技能组
            if(actionsItem.actionAllow){
              if(mixedBizScope) {
                // 只要当前坐席中角色与技能组中有当前步骤技能组的
                if (arrayContainsStr(mixedBizScope, actionsItem.actionQueue)) {
                  // 技能组
                  if (actionsItem.actionQueue.length > 0) {
                    actionsItem.actionQueue.forEach(item=>{
                      businessQueue.push(item)
                    })
                  }
                  this.batchBusiness.operateSelect.push(
                    {
                      value: actionsItem._id,
                      label: actionsItem.name,
                      actionRole: actionsItem.actionRole
                    }
                  )
                }
              }
            } else {
              if(mixedBizScope) {
                // 只要当前坐席中角色中有当前步骤角色的
                if (arrayContainsStr(mixedBizScope, actionsItem.actionRole)) {
                  //兼容老数据，之前是字符串
                  if(!Array.isArray(actionsItem.actionRole)){
                    actionsItem.actionRole = [actionsItem.actionRole]
                  }
                  actionsItem.actionRole.forEach(item=>{
                    businessRole.push(item)
                  })
                  this.batchBusiness.operateSelect.push(
                    {
                      value: actionsItem._id,
                      label: actionsItem.name,
                      actionRole: actionsItem.actionRole
                    }
                  )
                }
              }
            }
          }
        })
      },
      // 选择批量回退
      showTaskBack () {
        this.$refs.batchExecute.open({
          type: 'back',
          title: this.$t('business.returnBusiness'),
          busData: {
            _id: ''
          },
          condition: this.batchBusiness.argu
        })
      },
      // 选择某一工单步骤
      showTaskAction (key) {
        let actionId = key
        let stepId = ''
        if((this.qu.step instanceof Array) && this.qu.step.length === 1){
          stepId = this.qu.step[0]
        }
        let action = getFlowAction(stepId, actionId)
        let nextStepId = action.jumpTo
        let nextStep = getCache('businessFlowStep', nextStepId)
        if (nextStep.type === 'sys') { // 如果下一步是系统步骤，并且没有配置界面，则直接执行。
          let step = getCache('businessFlowStep', stepId)
          action = getFlowStepActionById(step.actions, actionId)
          let fields = action.actionFields
          if (fields.length === 0) {
            // 不填工单信息，直接提交
            let executeData = {actionId: actionId, master: 'sys'}
            this.busCompleteTip(executeData)
            return
          }
        }
        this.$refs.batchExecute.open({
          type: 'approval',
          title: this.$t('business.dealBusiness') + '-' + action.name,
          busData: {
            _id: '',
            stepId: this.qu.step[0],
            flow: this.qu.flow[0],
            actionId: actionId
          },
          condition: this.batchBusiness.argu
        })
      },
      // 流转到系统步骤提醒
      busCompleteTip (executeData) {
        let condition = this.batchBusiness.argu
        this.$confirm(this.$t('business.batchExecuteTip', {total: condition.total || 0}), this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          type: 'warning'
        }).then(() => {
          condition.data = executeData
          this.$store.dispatch('batchExecute', condition).then((res) => {
            if (res && res.success) {
              this.batchExecuteSuc(res)
            }
          })
        })
      },
      // 批量执行成功
      batchExecuteSuc (res,type) {
        if(type && type == 'back'){
          //批量退回工单需要单独处理message提示
          let msg = '',msgType = '';
          if(res.failCount == res.total){
            //全部不可退回
            msg = 'business.operateBackFail';
            msgType = 'error'
          }else if(res.successCount == res.total){
            //全部可退回
            msg = 'business.operateSuc';
            msgType = 'success'
          }else{
            //部分可退回
            msg = 'business.operateBackSome';
            msgType = 'warning'
          }
          this.$message({
            type:msgType,
            message:this.$t(msg)
          })
        }else{
          let message = res.failCount ? 'business.operateSucOther' : 'business.operateSuc'
          this.$message.success(this.$t(message))
        }
        this.checkNone()
        // 批处理成功后，刷新card
        this.$store.commit('business/REFRESH_LEFT', Math.random())
      },
      // 批量领取工单
      batchReceive () {
        // 统计埋点
        window._hmt && window._hmt.push(['_trackEvent', '工单', '工单批量领取'])
        if (this.batch.allChecked) {
          // 全选获取总数
          this.$store.dispatch(this.quAction, this.qu).then((res) => {
            if (res.success) {
              let _num = res.count || 0
              if (_num > 500) {
                // 大于10000条，提示重新查询
                this.$message.error(this.$t('message.batch_claim_business_max_limit'))
                return
              }
              // 批量领取提醒框
              let data = {total: _num, condition: deepClone(this.qu)}
              delete data.condition.queryCount
              delete data.condition.page
              delete data.condition.morePage
              this.batchReceiveDialog(data)
            }
          })
        } else {
          this.batchReceiveDialog({total: this.batch.checkedCount, ids: this.batch.batchItem})
        }
      },
      // 批量领取弹框确认
      batchReceiveDialog (data) {
        data.master = this.$store.state.session.sessionId
        this.$confirm(this.$t('business.batchReceiveTip', {total: data.total || 0}), this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('batchClaim', data).then((res) => {
            if (res && res.success) {
              let message = res.failCount ? 'business.operateSucOther' : 'business.batchReceiveSuc'
              this.$message.success(this.$t(message))
              this.checkNone()
              this.$store.commit('business/REFRESH_LEFT', Math.random())
            }
          })
        })
      },
      getExportCount () {
        if (this.batch.allChecked) {
           return this.$store.dispatch(this.quAction, this.qu).then((res) => {
            if (res.success) {
              return res.count
            }
          })
        } else {
          return Promise.resolve(this.batch.checkedCount)
        }
      },
      exportCustom () {
        this.getExportCount().then((_num) => {
          let limitNum = this.$getCache('exportTaskLimit') || {}
          if (limitNum.business && _num > limitNum.business) {
            this.$message.error(this.$t('business.exportBusinessLimit', {length: limitNum.business}))
            return
          }
          // 导出任务 50000
          if (_num > 50000) {
            this.exportDialog.fileType = 'csv'
            this.exportDialog.type = 'task'
            if (!this.exportDialog.agents.length) {
              this.$store.dispatch('getCache', {type: 'agents'}).then((res) => {
                this.exportDialog.agents = res.map((item) => {
                  return {value: item._id, label: `${item.displayName}[${item.exten}]`}
                })
              })
            }
            let session = this.$store.state.session
            this.exportDialog.downloadAgents = []
            if (session.user.type !== 'admin') {
              this.exportDialog.downloadAgents.push(session.sessionId)
            }
          } else {
            this.exportDialog.type = 'export'
          }
          this.exportDialog.isShow = true
          this.exportDialog.select = []
          let key = this.$store.state.session.sessionId + 'businessExportHeaders'
          let cacheHeaders = JSON.parse(window.localStorage.getItem(key))
          this.exportDialog.headers.forEach((item) => {
            if (cacheHeaders) {
              cacheHeaders.includes(item.value) && this.exportDialog.select.push(item.value)
            } else if (item.default) {
              this.exportDialog.select.push(item.value)
            }
          })
        })
      },
      deleteBus (self) {
        let data = {}
        if (self.batch.allChecked) {
          data = deepClone(this.$store.state.business.businessCondition)
          if (data.flow) {
            data.flow = typeof data.flow !== 'string' ? (data.flow.$in || []) : data.flow
          }
          if (data.step) {
            data.step = typeof data.step !== 'string' ? (data.step.$in || []) : data.step
          }
        } else {
          data = {_id: {$in: self.batch.batchItem}}
        }
        self.$store.dispatch('deleteBusiness', data).then(() => {
          this.$emit('allCountClear')
          self.$router.replace({path: '/index/business/'})
          self.$store.commit('business/REFRESH_LEFT', Math.random())
          self.$store.dispatch('refreshUndealNum')
          self.checkNone(self)
        })
      },
      // document Click监听函数
      listenerFun (e) {
        if (this.$refs.popover && !this.$refs.popover.$el.contains(e.target)) {
          this.batchBusiness.show = false
        }
      }
    },
    watch: {
      // clearChecked 变化 再次执行
      clearChecked: 'checkNone',
      'batch.isBatchShow' (nowV) {
        if (nowV === true && this.tabType === 'business_undeal') {
          // 有批量分配权限，且条件满足
          if (this.batch.operatorUndeal.length === 2 && this.qu.step && this.qu.step.length == 1) {
            this.batch.operatorUndeal[1].enabled = false
          } else if (this.batch.operatorUndeal.length === 2) {
            // 有批量处理权限，且条件不满足
            this.batch.operatorUndeal[1].enabled = true
          }
          this.batch.operator = this.batch.operatorCommon.concat(this.batch.operatorUndeal)
        } else if (nowV === true && this.tabType === 'business_my') {
          // 选择了某一工单类型和步骤
          let step = null
          if((this.qu.step instanceof Array) && this.qu.step.length === 1){
            step = this.$getCache('businessFlowStep', this.qu.step[0]) || {}
            // 如果step为第一步，不满足批处理
            if (step.isBegin) {
              // 如果是开始步骤 toottip提醒内容不同
              this.batch.operatorMy[0].tooltipContent = this.$t('business.executeSearchTip1')
            }
            this.batch.operatorMy[0].createUser = this.qu.ownercomCreateUser
            this.batch.operatorMy[0].enabled = step.isBegin
          }else if (this.batch.operatorMy.length) {
            this.batch.operatorMy[0].enabled = true
            this.batch.operatorMy[0].tooltipContent = this.$t('business.executeSearchTip')
          }
          this.batch.operator = this.batch.operatorCommon.concat(this.batch.operatorMy)
        } else if (nowV === true && this.tabType !== 'business_undeal') {
          this.batch.operator = this.batch.operatorCommon
        }
      }
    },
    components: {
      CustomerAvatar,
      CardBatch,
      NoRecord,
      BatchAssign,
      BatchExecute,
      noviceBoot,
      CustomExport
    },
    mounted () {
      document.addEventListener('click', this.listenerFun)
    },
    beforeDestroy () {
      document.removeEventListener('click', this.listenerFun)
    },
    beforeMount () {
      let self = this
      Promise.all([this.$store.dispatch('getCache', {type: 'businessFlow'}), this.$store.dispatch('getCache', {type: 'agents'})]).then(function () {
        self.cardloading = false
      })
      if (isHasFunc('func_task_delete', this.$store.state.session.user)) {
        this.batch.operatorCommon.push({name: 'public.delete', class: 'iconfont icon-shanchu', action: 'deleteTip'})
      }
      if (isHasFunc('func_task_export', this.$store.state.session.user)) {
        this.batch.operatorCommon.push({name: 'public.export', class: 'icon-daochu1', action: 'exportExcel'})
//        this.batch.operator.push({name: 'business.exportTask', class: 'icon-piliang', action: 'exportTask'})
      }
      if (isHasFunc('func_task_assign', this.$store.state.session.user)) {
        this.batch.operatorUndeal.push({name: 'business.batchAssign', class: 'icon-fenpei', action: 'batchAssign', tooltipContent: this.$t('business.assignSearchTip'), enabled: true})
      }
      // 获取最新呼吸灯是否展示
      this.updateGuidanceSuccess()
    }
  }
</script>
<style type="text/stylus" lang="stylus" scoped >
@import "../../../assets/common.styl"
.bus-card
  height 100%
  .one
    padding 0 0 2px 24px
    height 18px
    display: flex
    flex-direction row
    justify-content space-between
    .card-step
      color $cf-gray2
      font-weight bold
      text-align left
      overflow hidden
      display flex
    .card-time
      color: $cf-gray6
      flex-shrink 0
      flex-grow 1
      text-align right
      margin-left 10px
      .icon-shaohouchuli
        display inline-block
        color $c-main
    .card-step-item
      /*max-width 97px*/
      display inline-block
      text-overflow ellipsis
      overflow hidden
      white-space nowrap
    .b-step
      color $c-bus-step
    .finish
      color $cf-gray5
  .two
    display flex
    flex-direction row
    line-height 20px
    font-size 12px
    color $cf-gray4
.card-left
  width: 24px
  min-width 24px
  text-align center
  i
    font-size 16px
    display block
  .process-timeout
    line-height 20px
    color: $c-pink
  .icon-yiguanzhu
    line-height 18px
    color $c-main
.card-right
  display flex
  flex-direction column
  line-height 20px
  width calc(100% - 24px)
  flex-grow 1
  .card-customer
    display flex
    flex-direction row
    justify-content space-between
    .customer-name
      color $cf-gray2
      text-overflow ellipsis
      overflow hidden
      white-space nowrap
      flex-grow 1
      padding-right 10px
    .creator-master
      display flex
  .deleteCus
    text-decoration line-through
  .icon-dailingqu
    margin 0 5px
  .summary
    padding-top 1px
    display -webkit-box
    -webkit-line-clamp: 2;
    overflow: hidden;
    white-space normal
    line-height 18px
  .name
    max-width 52px
    text-overflow ellipsis
    overflow hidden
    white-space nowrap
  .tasktome
    margin-top 1px
    padding 1px 6px
    border 1px solid $c-main
    border-radius 4px
    line-height 14px
    max-width 45px
    height 18px
    box-sizing border-box
    color $c-main
    font-size 12px
    &:hover
      background: $c-main;
      border-color: $c-main;
      color: #fff;
.card-detail
  background-color $c-bus-tip
  .card-detail-tittle
    color $cf-gray2
    font-weight bold
    padding-bottom 10px
  .card-detail-item
    line-height 22px
  .data-name
    color $cf-gray4
    min-width 50px
    width 50px
    padding-right 24px
  .break-all
    color $cf-gray2
    word-break break-all
    white-space pre-line
  .data-padding
    padding-top 15px
.el-menu-item
  height auto
  line-height inherit
  padding 0
  background-color $cf-white
.el-menu-item.custom-is-active
  background-color $c-card-active
.card:hover
.card:active
  background-color $c-card-hover
.visible
  .fake-label
    margin -12px 0 0 -8px
    height 90px
.card
  width 100%
  box-sizing border-box
  padding 0 5px
  border-bottom 1px solid $c-border1
  display flex
  cursor pointer
  flex-direction column
  .none
    display none

.option
  display flex
.option.disabled
  color $cf-level3
  i
    color $cf-level3
  &:hover
    cursor not-allowed
    color $cf-level3
.batch-step
  font-size 12px
  line-height 27px
  text-align center
  &:hover
    background-color #f5f7fa
    cursor pointer
    color $c-main
.batch-step.pink
  color $c-pink
.flow-icon1
  color $c-pink !important
  display inline-block
.flow-icon2
  color #E6A23C !important
  display inline-block
.flow-icon3
  color $c-main !important
  display inline-block
.flow-icon4
  color #58970f !important
  display inline-block
</style>
